package com.tiancan.design.code.service.impl;

import com.tiancan.design.code.bean.pojo.Code;
import com.tiancan.design.code.dao.CodeDao;
import com.tiancan.design.code.service.CodeService;
import com.tiancan.design.code.service.SendServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/** @author tiancan */
@Service
public class CodeServiceMySqlImpl implements CodeService {
  @Autowired private CodeDao codeDao;
  @Autowired private SendServiceFeignClient sendServiceFeignClient;

  @Override
  public Boolean createCode(String email) {
    Code code = new Code(email);
    try {
      codeDao.save(code);
    } catch (Exception ex) {
      ex.printStackTrace();
      return false;
    }
    return sendServiceFeignClient.sendEmail(email, code.getCode());
  }

  @Override
  public Integer validate(String email, String code) {
    List<Code> listByEmailAndCode = codeDao.findListByEmailAndCode(email, code);
    if (listByEmailAndCode == null || listByEmailAndCode.size() != 1) {
      return 1;
    }
    Code c = listByEmailAndCode.get(0);
    Boolean expire = c.isExpire();
    return expire ? 1 : 0;
  }
}
